﻿using System;
using System.Collections.Generic;
using System.Web.Services.Protocols;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Editors {
    public partial class GroupExpEdit : SessionPage {

        private GroupExp groupExp;

        protected void Page_Load(object sender, EventArgs e) {
            string id = Request.QueryString["id"];
            Form.Action = ResolveUrl("~/forms/Editors/GroupExpEdit.aspx");
            var ms = new MainService();
            if (id != null) {
                Form.Action += "?id=" + id;
                groupExp = ms.LoadGroupExp(GetSession(), int.Parse(id));
            } else {
                groupExp = new GroupExp();
                groupExp.Group = "";
                groupExp.Secretary = "";
                groupExp.SpecialityList = new Speciality[0];
            }
            Speciality[] specialityList = ms.GetSpecialityList(GetSession(), true);
            foreach (var speciality in specialityList) {
                var listItem = new ListItem(speciality.Title, "" + speciality.Id);
                listItem.Attributes["type"] = speciality.GetType().Name;
                comboSpeciality.Items.Add(listItem);
            }
            if (!IsPostBack) {
                tfGroup.Text = groupExp.Group;
                tfChairman.Text = groupExp.Chairman;
                tfSecretary.Text = groupExp.Secretary;
            }
            //hfMembers.Value = "";
            //hfQuestions.Value = "";
            //hfSpecialities.Value = "";
            foreach (var speciality in groupExp.SpecialityList) {
                var row = new TableRow();
                var cellRemove = new TableCell();
                var cellSpec = new TableCell();
                cellRemove.Width = 24;
                cellRemove.Controls.Add(new HyperLink() {
                    CssClass = "delete deleteSpecialityFromGroup",
                    ID = "" + speciality.Id
                });
                cellSpec.Text = speciality.Title;
                row.Cells.Add(cellRemove);
                row.Cells.Add(cellSpec);
                tblSpecialityList.Rows.Add(row);
                if (!IsPostBack) {
                    hfSpecialities.Value += ";" + speciality.Id;
                }
            }

            bool create = groupExp.Id == 0;
            GroupExpMember[] groupExpMemberList = ms.GetGroupExpMemberListByGroupExp(GetSession(), groupExp);
            foreach (var member in groupExpMemberList) {
                var row = new TableRow();
                var cellDelete = new TableCell();
                cellDelete.Width = 18;
                var cellMember = new TableCell();
                cellDelete.Controls.Add(new HyperLink() {
                    ID = "" + member.Id,
                    NavigateUrl = "",
                    CssClass = "delete member"
                });
                cellMember.Text = member.Member;
                if (!IsPostBack) {
                    hfMembers.Value += ";" + member.Id + "=" + member.Member;
                }

                row.Cells.Add(cellDelete);
                row.Cells.Add(cellMember);
                tblMembers.Rows.Add(row);
            }
            Question[] questions = ms.GetQuestionListByGroupExp(GetSession(), groupExp);
            foreach (var question in questions) {
                var row = new TableRow();
                var cellDelete = new TableCell();
                cellDelete.Width = 18;
                var cellContent = new TableCell();
                cellDelete.Controls.Add(new HyperLink() {
                    ID = "" + question.Id,
                    NavigateUrl = "",
                    CssClass = "delete question"
                });
                cellContent.Text = question.Context;
                if (!IsPostBack) {
                    hfQuestions.Value += ";" + question.Id + "=" + question.Context;
                }

                row.Cells.Add(cellDelete);
                row.Cells.Add(cellContent);
                tblMembers.Rows.Add(row);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e) {
            try {
                var ms = new MainService();
                var valMem = hfMembers.Value;
                var valQuest = hfQuestions.Value;
                var valSpec = hfSpecialities.Value;
                string[] splitMembers = valMem.Split(';');
                var splitQuestions = valQuest.Split(';');
                var splitSpecs = valSpec.Split(';');

                List<int> memIds = new List<int>();
                List<int> questIds = new List<int>();
                List<int> specIds = new List<int>();

                for (int i = 1; i < splitSpecs.Length; i++) {
                    specIds.Add(Convert.ToInt32(splitSpecs[i]));
                }

                groupExp.Chairman = tfChairman.Text;
                groupExp.Group = tfGroup.Text;
                groupExp.Secretary = tfSecretary.Text;

                var specialities = new List<Speciality>();
                for (int i = 0; i < specIds.Count; i++) {
                    specialities.Add(ms.LoadSpeciality(GetSession(), specIds[i]));
                }
                groupExp.SpecialityList = specialities.ToArray();

                groupExp = ms.SaveGroupExp(GetSession(), groupExp);

                for (int i = 1; i < splitMembers.Length; i++) {
                    string[] strings = splitMembers[i].Split('=');
                    int id = Convert.ToInt32(strings[0]);
                    string text = strings[1];
                    var groupExpMember = new GroupExpMember() { GroupExp = groupExp, Id = id, Member = text };
                    var member = ms.SaveGroupExpMember(GetSession(), groupExpMember);
                    memIds.Add(member.Id);
                }

                for (int i = 1; i < splitQuestions.Length; i++) {
                    string[] strings = splitQuestions[i].Split('=');
                    int id = Convert.ToInt32(strings[0]);
                    string text = strings[1];
                    var question = new Question() { GroupExp = groupExp, Id = id, Context = text };
                    var member = ms.SaveQuestion(GetSession(), question);
                    questIds.Add(member.Id);
                }
                ms.SetGroupMembersToGroup(GetSession(), groupExp, memIds.ToArray());
                ms.SetQuestionsToGroup(GetSession(), groupExp, questIds.ToArray());

                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }
    }
}